package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.jt.mapper.ItemDescMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.EasyUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jt.mapper.ItemMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;


@Service
public class ItemServiceImpl implements ItemService {
	
	@Autowired
	private ItemMapper itemMapper;
	@Autowired
	private ItemDescMapper itemDescMapper;

	/*
	查询第一页
	select * from tb_item limit 起始位置，查询条数
	select * from tb_item limit 0,20
	第二页
	select * from tb_item limit 20,20
	第三页：select * from tb_item limit 40,20
	第n页
	第三页：select * from tb_item limit (page-1)rows,20
	@param page
	@param rows
	 */
	@Override
	public EasyUITable findItemByPage(int page, int rows) {
//		long total = itemMapper.selectCount(null);
//		//1.手写分页
//		int startIndex = (page - 1) * rows;
//		List<Item> itemList = itemMapper.findItemByPage(startIndex,rows);
		IPage mpPage = new Page(page,rows);
		QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc("updated");
		mpPage = itemMapper.selectPage(mpPage, queryWrapper);
		long total = mpPage.getTotal();
		List<Item> itemList = mpPage.getRecords();
		return new EasyUITable(total, itemList);
	}
	/*添加操作*/
	@Transactional//开启事务控制
	@Override
	public void saveItem(Item item,ItemDesc itemDesc) {
		//Date date = new Date();
		//item.setStatus(1).setCreated(date).setUpdated(date);
		item.setStatus(1);
		//MP用法：如果完成主键自增，则自动的实现数据到回显
		itemMapper.insert(item);
		itemDesc.setItemId(item.getId());
		itemDescMapper.insert(itemDesc);
	}
	/*商品编辑操作*/
	@Override
	public void updateItem(Item item, ItemDesc itemDesc) {
		itemMapper.updateById(item);
		itemDesc.setItemId(item.getId());
		itemDescMapper.updateById(itemDesc);
	}
	/*
	sql:delete from tb_item where id in(100,)
	 */
	@Override
	public void deleteItem(Long[] ids) {
		List<Long> longIds = Arrays.asList(ids);
		itemMapper.deleteBatchIds(longIds);
		itemDescMapper.deleteBatchIds(longIds);
	}
	/*商品上下架*/
	@Override
	public void updateStatus(Long[] ids, Integer status) {
		//以MP的方法操作数据库 只修改状态码
//		Item item = new Item();
//		item.setStatus(status);
//		QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
//		queryWrapper.in("id",ids);
//		itemMapper.update(item,queryWrapper);
		itemMapper.updateStatus(ids,status);
	}

	@Override
	public ItemDesc findItemDescById(Long itemId) {
		return itemDescMapper.selectById(itemId);
	}

}
